package com.lmpop.trade.quartz;

import com.lmpop.frame.dao.DbmInterf;
import com.lmpop.frame.dao.IbatisDbmImpl;
import com.lmpop.trade.ts_task.Ts_taskInfo;
import java.lang.reflect.Method;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;

public class UpdateTimerServlet extends HttpServlet
{
  private Timer timer;
  private static Ts_taskInfo taskInfo = null;
  private static DbmInterf dbmMgr = null;

  public UpdateTimerServlet()
  {
    this.timer = null;
  }

  public void init()
    throws ServletException
  {
    this.timer = new Timer(true);
    taskInfo = new Ts_taskInfo();
    dbmMgr = new IbatisDbmImpl();
    this.timer.schedule(new MyTask(), 0L, 86400000L);
  }

  public void destroy()
  {
    this.timer.cancel();
  }

  private static void invokeMethodList(List tradeList)
  {
    String result = "";
    try {
      if ((tradeList != null) && (tradeList.size() > 0)) {
        Hashtable bpmMap = new Hashtable();
        Map paramMap = new Hashtable();
        for (int i = 0; i < tradeList.size(); i++) {
          String task_id = ""; String task_method = ""; String task_param = "";
          bpmMap = (Hashtable)tradeList.get(i);
          if (bpmMap.get("task_id") != null)
            task_id = bpmMap.get("task_id").toString();
          if (bpmMap.get("task_method") != null)
            task_method = bpmMap.get("task_method").toString();
          if (bpmMap.get("task_param") != null) {
            task_param = bpmMap.get("task_param").toString();
          }
          Class bpmClass = Class.forName("com.lmpop.trade.quartz.UpdateTimer");
          Object objBpm = null;
          try {
            objBpm = bpmClass.newInstance();
            Method bpmMethod = objBpm.getClass().getDeclaredMethod(task_method.trim(), new Class[] { String.class });
            result = (String)bpmMethod.invoke(objBpm, new Object[] { task_param });

            paramMap.put("task_id", task_id);
            if (result.equals("1"))
              paramMap.put("is_exec", "0");
            else {
              paramMap.put("is_exec", result);
            }
            dbmMgr.updateSql("updateTs_task", paramMap);
          } catch (InstantiationException e) {
            result = "2";
            e.printStackTrace();
          }
        }
      }
    }
    catch (Exception e) {
      result = "2";
      e.printStackTrace();
    }
  }

  static class MyTask extends TimerTask
  {
    public void run()
    {
      List tradeList = UpdateTimerServlet.taskInfo.getAllTaskList();
      UpdateTimerServlet.invokeMethodList(tradeList);
    }
  }
}